#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
import json
import sys
import urllib2

def getWorkouts(page=0,size=100):
    count = page*size;
    conn = MySQLdb.connect(host="keepfitdb.mysql.rds.aliyuncs.com",user="for_ol",passwd="Abcd1234",port=3306)
    cur = conn.cursor()
    conn.select_db('coacht')
    sql = "select id,actionlist from t_user_workout where workout_type = 0  limit %d , %d " % (count , size);
    cur.execute(sql)
    rows = cur.fetchall()
    cur.close()
    conn.close()
    return rows
def updateWorkout(id,actionCount,groupCount):
    conn = MySQLdb.connect(host="keepfitdb.mysql.rds.aliyuncs.com",user="for_ol",passwd="Abcd1234",port=3306)
    cur = conn.cursor()
    conn.select_db('coacht')
    cur.execute('update t_user_workout set action_count = %s , group_count = %s where id = %s',(actionCount,groupCount,id))
    cur.close()
    conn.commit()
    conn.close()

if __name__ == "__main__":
    size = 100
    page = 0
    while True:
        workouts = getWorkouts(page,size)
        for workout in workouts:
            try:
                actionCount = 0;
                groupCount = 0;
                id = workout[0]
                workoutData = json.loads(workout[1])
                for course in workoutData:
                    rep = course['repeat_times']
                    actions = course['actions']
                    actionArr = actions.split(',')
                    for action in actionArr:
                        actionInfo = action.split(':')
                        actionId = actionInfo[0]
                        times = actionInfo[1]
                        duration = actionInfo[2]
                        actionCount += int(times)*int(rep);
                        groupCount += int(rep)
                        # print actionId,times,duration

                print id,actionCount,groupCount
                updateWorkout(id,actionCount,groupCount)
            except:
                print str(id)+"数据异常"
        page += 1
        if len(workouts) < 100:
            break
